package dlg.code.producer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ItemBuffer {

    private String[] buffer;
    private int size;
    private volatile int wPtr;
    private volatile int rPtr;
    private volatile int count;

    public Lock lock;
    public Condition notFull;
    public Condition notEmpty;

    public ItemBuffer(int size) {
        buffer = new String[size];
        this.size = size;

        lock = new ReentrantLock();
        notEmpty = lock.newCondition();
        notFull = lock.newCondition();
    }

    public int getCount() {
        return count;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public boolean isFull() {
        return count == size;
    }

    public void produce(String data) {
        if (wPtr == size) {
            wPtr = 0;
        }
        buffer[wPtr++] = data;
        count++;
    }

    public String take() {
        if (rPtr == size) {
            rPtr = 0;
        }
        count--;
        return buffer[rPtr++];
    }

}
